package com.fhc.view

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber


@Composable
fun rememberFhcComoBoxState(): MutableState<KeyLabel?> = remember { mutableStateOf(null) }
@Composable
fun FhcComoBox(modifier: Modifier = Modifier,
               label: @Composable (() -> Unit)? = null,
               selectedKeyLabel: MutableState<KeyLabel?> = rememberFhcComoBoxState(),
               onValueChange: (Int) -> Unit? = {},
               colors: TextFieldColors = OutlinedTextFieldDefaults.colors(),
               items: MutableState<List<KeyLabel>>,
               itemContent: @Composable (ColumnScope.(idx: Int, it:KeyLabel) -> Unit) = {idx, it->
                   Row {
                       if (it.selected.value) {
                           Icon(
                               imageVector = Icons.Default.Check, "contentDescription",
                               modifier = Modifier.padding(start = 8.dp, end = 8.dp),
                               tint = Color.Blue
                           )
                       } else {
                           Box(
                               modifier = Modifier.padding(start = 8.dp, end = 8.dp),
                           )
                       }
                       Text(
                           text = it.label, maxLines = 1, overflow = TextOverflow.Ellipsis,
                           modifier = Modifier.padding(start = 8.dp), color = if (it.selected.value) Color.Blue else Color.Black
                       )
                   }
               } )
{

    // Declaring a boolean value to store
    // the expanded state of the Text Field
    var mExpanded by remember { mutableStateOf(false) }

    selectedKeyLabel.value?.selected?.value = true
    for (i in 0..items.value.size-1) {
        items.value[i].selected.value = (items.value[i].key == selectedKeyLabel.value?.key)
    }

    val coroutineScope: CoroutineScope = rememberCoroutineScope()
    var mSelectedText by remember { mutableStateOf("") }
    val scrollState = rememberScrollState()
    mSelectedText = selectedKeyLabel.value?.label ?: ""
    var mTextFieldSize by remember { mutableStateOf(Size.Zero)}

    // Up Icon when expanded and down icon when collapsed
    val icon = if (mExpanded)
        Icons.Filled.KeyboardArrowUp
    else
        Icons.Filled.KeyboardArrowDown

    Column(modifier) {
        Box {
            OutlinedTextField(
                value = mSelectedText,
                onValueChange = {  it->
                    items.value.forEach { item ->
                        item.selected.value = (item.label == it)
                        if(item.label == it) mSelectedText = item.label
                        selectedKeyLabel.value = item
                    }
                },
                maxLines = 1,
                readOnly = true,
                modifier = Modifier.fillMaxWidth()
                    .onGloballyPositioned { coordinates ->
                        // This value is used to assign to
                        // the DropDown the same width
                        mTextFieldSize = coordinates.size.toSize()
                    }.focusProperties {
                        canFocus = false // 完全禁止获得焦点
                    },
                label = label,
                trailingIcon = {
                    Icon(
                        icon, "contentDescription",
                        Modifier.focusProperties {
                            canFocus = false // 完全禁止获得焦点
                        }.clickable { mExpanded = !mExpanded }
                        , tint = colors.focusedTextColor
                    )
                },
                colors =colors
            )
            // 给OutlinedTextField添加点击事件
            Box(modifier =Modifier
                .size(
                    with(LocalDensity.current){mTextFieldSize.width.toDp()},
                    with(LocalDensity.current){mTextFieldSize.height.toDp()}
                )
                .background(Color.Transparent).clickable {
                    mExpanded = !mExpanded
                })
        }
        // Create a drop-down menu with list of cities,
        // when clicked, set the Text Field text as the city selected
        DropdownMenu(
            expanded = mExpanded,
            onDismissRequest = { mExpanded = false },
            modifier = Modifier
                .width(with(LocalDensity.current){mTextFieldSize.width.toDp()})
        ) {
            Column(
                modifier = Modifier.heightIn(max = 260.dp).fillMaxWidth().verticalScroll(scrollState)
            ) {
                items.value.forEachIndexed { idx, it ->
                    DropdownMenuItem(modifier = Modifier.onSizeChanged{size->
                        coroutineScope.launch {
                            if (it.selected.value) {
                                scrollState.scrollTo(size.height * (if (idx > 4) idx - 2 else idx))
                            }
                        }
                        Timber.i("----onSizeChanged----------%s", size)
                    },text = {
                        itemContent(idx, it)
                    }, onClick = {
                        selectedKeyLabel.value?.selected?.value = false
                        selectedKeyLabel.value =  items.value[idx]
                        for (i in 0..items.value.size - 1) {
                            items.value[i].selected.value = (items.value[i].key == selectedKeyLabel.value?.key)
                        }
                        selectedKeyLabel.value?.selected?.value = true
                        onValueChange(idx)  //, selectedKeyLabel.value
                        mExpanded = false
                    })
                }
            }
        }
    }
}
